/* eslint-disable */
import xlsx from '@/util/xlsx'
import uuid from '@/util/uuid'
import formatClass from '@/util/formatClass'
import cookie from '@/util/cookie'
import {importDept} from '@/api/deptApi'
import {importTeacher} from '@/api/teacherApi'
import {importStudent, addLearnApi} from '@/api/studentListApi'
import {dictionaryvalue, getPeroidsList, getSchoolStage, getGradeList} from '@/api/schoolApi'

export let deptMap = {
    部门名称: {col: 'name', required: true},
   
    部门编码: {col: 'code', reg: /^\d+$/, desc: '只允许填写数字'},
    上级部门: {col: 'parentName'}
}
export let teacherMap = {
        职工姓名: {col: 'name', required: true},
        性别: {col: 'gender'},
        身份证号码: {col: 'idNumber', reg: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, desc: '身份证号码不正确'},
        手机号码: {col: 'cellPhoneNum', reg: /^1[3456789]\d{9}$/, required: true, desc: '手机号码不正确', noRepeat: true},
        教学科目: {col: 'subJectName', reg: ''},
        授课班级: {col: 'importTeacherClassMaps', reg: '', desc: '班级不正确', isClass: true, isCheckGrade: true},
        担任班主任班级: {col: 'masterClass', reg: '', desc: '班级不正确', isClass: true, isCheckGrade: true},
        所在部门: {col: 'deptNameList', reg: ''}
}
// /^((([0-9一二三四五六七八九]年级)|(高[123一二三]))[0-9一二三四五六七八九]+班[，、,\.]?)*$/
export let studentMap = {
        学生姓名: {col: 'name', reg: '', required: true},
        学籍号: {col: 'studentCode', reg: '', noRepeat: true},
        身份证号码: {col: 'idNumber', reg: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, desc: '身份证号码不正确', noRepeat: true},
        性别: {col: 'gender', reg: ''},
        所属学段: {col: 'stageName', required: true, reg: '', list: [], isListNum: false},
        学级: {col: 'startYear', reg: '', required: true, list: [], isListNum: true},
        年级: {col: 'gradeName', required: true, list: [], isListNum: false, isClass: true},
        班级: {col: 'className', reg: /^[0-9一二三四五六七八九]+班$/, desc:'格式如：1班', required: true, isClass: true},
        入学年月: {col: 'startDate', reg: /^[0-9]{4}[\/\.-]{1}[0-9]{1,2}$/, desc: '格式如：2020-01', required: true},

        
        家长姓名: {col: 'parentName', reg: '', required: true},
        家长手机号码: {col: 'parentPhone',  reg: /^1[3456789]\d{9}$/, required: true, desc: '手机号码不正确'},
        关系: {col: 'relationCode', reg: '', list: [], isListNum: false}
}

let gradeList = []
let peroidsList = []

export const getPeroidsByStageName = (stageName) => {
    var list = []
    for (var item of peroidsList) {
        if (stageName == item.stageName) {
            list.push(item.name)
        }
    }
    return list
}

export const getGradeByName = ({stageName, peroidName}) => {
    var list = []
    for (var item of peroidsList) {
        if (stageName == item.stageName && getNumber(item.name) == getNumber(peroidName)) {
            list.push(item.gradeName)
        }
    }
    return list
}

export const setGradeList = async (params) => {
     var res = await getGradeList(params)
      var items = res.items
      var list = items.map(obj => obj.name)
      gradeList = list
    //   studentMap['年级'].list = list
    
}

export const setStartYearList = async (params) => {
    var res = await getPeroidsList(params)
    peroidsList = res
    
    var list = res.map(obj => obj.name)
    // studentMap['学级'].list = list
}

export const setRelationList = async () => {
    var res = await dictionaryvalue({typeCode: 'FamilyRelation'})
    var list = res.map(obj => obj.valName)
    studentMap['关系'].list = list
}
export const setStageList = async (schoolId) => {
    var res = await getSchoolStage(schoolId)
    var items = res.items
    var list = items.map(obj => obj.name)
    studentMap['所属学段'].list = list
}

export const setSubjectList = (list) => {
    // teacherMap['教学科目'].list = list
    // teacherMap['教学科目'].multiple = true
}

 
export const check = ({required, reg, desc, val, col, list, isListNum, isCheckGrade, dataList, noRepeat}) => {
        if (required) {
            if (!val) {
                return {legal: false, desc: '不能为空'}
            }
        }

        if (list && val) {
            console.log(list)
            var isHave = false
            for (var item of list) {
                if (isListNum) {
                    if (getNumber(item) == getNumber(val)) {
                        isHave = true
                    }
                } else {
                    if (item == val) {
                        isHave = true
                    }
                }
                
            }
            console.log('isHave:', isHave)
            return  {legal: isHave, desc: '不存在的值'}
        }

        if (reg && val) {
            if (!reg.test(val)) {
                return  {legal: false, desc: desc}
            }
        }

        if (isCheckGrade && val) {
            if (!checkGrade(val)) {
                return {legal: false, desc: '班级不正确'}
            }
        }

        return {legal: true, desc: ''}
}

export const checkList = ({list, map}) => {
        var data = [].concat(list)
        console.log('dataList:', data)
        for (var item of data) {              
            for (var key in map) {
                var col = map[key].col
                
                // 学级
                if (col == 'startYear') {
                    var list = getPeroidsByStageName(item.stageName.val)
                } else if (col == 'gradeName') {
                    var list = getGradeByName({stageName: item.stageName.val, peroidName: item.startYear.val})
                } else {
                    var list = map[key].list
                }
                map[key].list = list
               
                var multiple = map[key].multiple
               
                
                var checkObj =  Object.assign({}, map[key]) 
                checkObj.val = item[col].val
                checkObj.dataList = data
                
             
                var result = check(checkObj)
                item[col].legal = result.legal
                item[col].desc = result.desc

                if (list) {
                    item[col].list = list
                    item[col].multiple = multiple
                }
            }
        }
        return data
}

const checkGrade = (str) => {
    var reg = /^([0-9一二三四五六七八九]年级)|(高[123一二三](年级)?).*$/
    var strList = splitByAll(str)

    var flag = true
    for (var item of strList) {
        var result = reg.exec(item)
        var g = ''
        if (result && result[1]) {
            g = result[1]
        }
        if (result && result[2]) {
            g = result[2]
        }
        if (!gradeList.includes(g)) {
            flag = false
        }
    }
    
    return flag
}

const clearItem = (item) => {
    for (var key in item) {
        var val = item[key]
        key = key.replace(/[\s\*]+/g, '')

        if (!val) {
            val = ''
        }
        val = (val + '').replace(/\s+/g, '')
        item[key] = val
    }
}

const toEnglish = ({data, map}) => {
    
    var list = []
        
    for (var item of data) {
        clearItem(item)
        var obj = {}
        for (var key in map) {
            var val = item[key]
            if (!val) {
                val = ''
            }
          
            var col = map[key].col
                
            obj[col] = val
        }
        list.push(obj)
    }
    return list
}

const convert = ({data, map}) => {
        var list = []
        
        for (var item of data) {
            clearItem(item)
            var obj = {}
            for (var key in map) {
                var val = item[key]
                if (!val) {
                    val = ''
                }

                if (map[key].isClass) {
                    val = formatClass(val)
                }
                if (map[key].isArr) {
                    val = splitByAll(val)
                }

              
                var col = map[key].col
                    
                obj[col] = {
                    val: val,
                    ch: key
                }
            }
            list.push(obj)
        }
        return list
}

export const createData = ({data, map}) => {
    var list = convert({data, map})
    list = checkList({list, map})
    return list
}

 const readData = async ({file, fileId, check, map}) => {
     
    var res = await xlsx.read(file)
    if (check) {
        var list = createData({data: res, map})
    
        for (var item of list) {
            item.fileId = fileId
            item.id = uuid()
        }
    } else {
        var list = toEnglish({data: res, map})
    }
    return list
}

export const readDept = async ({file, fileId, check}) => {
    
    return await readData({file, fileId, check, map: deptMap})
}

export const readTeacher = async ({file, fileId, check}) => {
    return await readData({file, fileId, check, map: teacherMap})
}

export const readStudent = async ({file, fileId, check}) => {
    return await readData({file, fileId, check, map: studentMap})
}

const formatData = (list) => {
    list = JSON.parse(JSON.stringify(list))
    for (var item of list) {
        delete item.id
        delete item.fileId
        for (var key in item) {
            if (typeof item[key] == 'object') {
                item[key] = item[key].val
            }
            item[key] = item[key].replace(/\s+/g, '')
        }
    }
    return list
}

const splitByAll = (str) => {
    var arr = str.split(/[,.，。、\/]/)
    for (var i = arr.length - 1; i >= 0; i--) {
        if (!arr[i]) {
            arr.splice(i, 1)
        }
    }
    return arr
}

function formateDate (str) {
    str = str.replace(/\//g, '-')
    
    var date = new Date(str)
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    if (month < 10) {
        month = '0' + month
    }
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var hour = date.getHours()
    hour = hour < 10 ? '0' + hour : hour
    var minute = date.getMinutes()
    minute = minute < 10 ? '0' + minute : minute
    var sec = date.getSeconds()
    sec = sec < 10 ? '0' + sec : sec
    return year + '-' + month + '-' + d + ' '+hour+':'+minute+':' + sec
}

function getNumber (str) {
    var num= str.replace(/[^0-9]/ig,"")
    return num
}

export const importDeptData = async ({list,schoolId}) => {
    
    list = formatData(list)
    
    var params = {
        schoolId: schoolId,
        body: list
     }
    
     await importDept(params)
}

export const importTeacherData = async ({list, schoolId}) => {
    list = formatData(list)
    for (var item of list) {
        if (item.gender == '男') {
            item.gender = true
        } else {
            item.gender = false
        }
        
        item.subJectName = splitByAll(item.subJectName)
        item.deptNameList = splitByAll(item.deptNameList)

      
        item.importTeacherClassMaps = splitByAll(item.importTeacherClassMaps)
        item.masterClass = splitByAll(item.masterClass)


        var yuList = []
        item.importTeacherClassMaps = item.importTeacherClassMaps.map((name) => {
            var obj = {
                className: name,
                isChargeTeacher: false,
                isTeach: true
            }
           
            return obj
        })
        item.masterClass = item.masterClass.map((name) => {
            var obj = {
                className: name,
                isChargeTeacher: true,
                isTeach: false
            }
            return obj
        })
        
        var yuList = []
        for (var master of item.masterClass) {
            var isHave = false
            for (var teach of item.importTeacherClassMaps) {
                if (teach.className == master.className) {
                    teach.isChargeTeacher = true

                    isHave = true
                }
            }
            if (!isHave) {
                yuList.push(master)
            }
        }
        
        item.importTeacherClassMaps = item.importTeacherClassMaps.concat(yuList)
        

        delete item.masterClass
    }
    var params = {
        schoolId: schoolId,
        body: {
          items: list
        }
    }
    console.log(params)
    await importTeacher(params)
}



export const importStudentData = async ({list, schoolId}) => {
    list = formatData(list)
    for (var item of list) {
        if (item.gender == '男') {
            item.gender = true
        } else {
            item.gender = false
        }
      

        item.startDate = formateDate(item.startDate)

        if (item.parentPhone) {
            item.parentPhone = splitByAll(item.parentPhone)[0]
        }

        item.startYear = getNumber(item.startYear)
       
    }
    
    var params = {
            schoolId: schoolId,
            body: list
        }
    console.log(params)
    await importStudent(params)
}

